/*
 * This is management interface for agents, implemented as a singleton
 * More documentation coming
 */

package sk.stuba.fei.ut.snmpmanager;

import java.util.ArrayList;
import java.util.UUID;

import android.content.Context;
import android.util.Log;

public class AgentManager
{
	// debugging TAG
	private static final String TAG = "AgentManager";
	// filename in private storage to store data into
	private static final String FILENAME = "snmpagents.json";
	// Singleton itself, see design patters: Singleton pattern
	private static AgentManager sAgentManager;

	// represents List of Agents managed by this class
	private ArrayList<Agent> mAgents;
	// Instance of class that handles data savings
	private AgentJSONSerializer mSerializer;
	// Context is which part of app called us, see android documentation
	private Context mAppContext;

	private AgentManager( Context appContext )
	{
		mAppContext = appContext;
		mSerializer = new AgentJSONSerializer( mAppContext, FILENAME );
		try
		{
			mAgents = mSerializer.loadAgents();
		}
		catch ( Exception e )
		{
			mAgents = new ArrayList<Agent>();
			Log.e( TAG, "Error loading agents", e );
		}
	}

	// return Manager itself, if do not exist create one
	public static AgentManager get( Context c )
	{
		if ( sAgentManager == null )
		{
			sAgentManager = new AgentManager( c.getApplicationContext() );
		}
		return sAgentManager;
	}

	public ArrayList<Agent> getAgents()
	{
		return mAgents;
	}

	// Go through all Agents, if exists return immediately, if not return null
	public Agent getAgent( UUID id )
	{
		for ( Agent agent : mAgents )
		{
			if ( agent.getID().equals( id ) ) return agent;
		}

		return null;
	}

	// Add agent to the collection
	public void addAgent( Agent agent )
	{
		mAgents.add( agent );
	}

	public void deleteAgent( Agent agent )
	{
		mAgents.remove( agent );
	}

	public boolean saveAgents()
	{
		try
		{
			mSerializer.saveAgents( mAgents );
			Log.i( TAG, "Saved to file " );
			return true;
		}
		catch ( Exception e )
		{
			Log.e( TAG, "Error during save", e );
			return false;
		}
	}

	// TODO: add methods to work with SNMPManager and Trap and Pool services

	// MH-edit
	public String getAgent_polling()
	{
		for ( Agent agent : mAgents )
		{
			if ( agent.isPolled() ) return agent.getIpv4Address();

			;

		}
		return null;
	}

}
